// MultiThread.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <Windows.h>

#define MAX_THREAD		4
#define MAX_FILE		4

static CRITICAL_SECTION g_SectionWrite[MAX_FILE];
// static CRITICAL_SECTION g_SectionWriteB;
// static CRITICAL_SECTION g_SectionWriteC;
// static CRITICAL_SECTION g_SectionWriteD;

static HANDLE g_hThreadCreateEvent = NULL;

DWORD __stdcall MyThreadProc(LPVOID lpThreadParameter);

int _tmain(int argc, _TCHAR* argv[])
{
	for (int i = 0; i < MAX_FILE; ++i)
	{
		InitializeCriticalSection(&g_SectionWrite[i]);
	}

	g_hThreadCreateEvent = CreateEvent(NULL, FALSE, FALSE, L"MyThreadCreateFinished");
	HANDLE hThread[MAX_THREAD];
	for (int i = 1; i <= MAX_THREAD; ++i)
	{
		hThread[i-1] = CreateThread(NULL, 0, &MyThreadProc, &i, 0, NULL);
		WaitForSingleObject(g_hThreadCreateEvent, INFINITE);
	}
	WaitForMultipleObjects(MAX_THREAD, hThread, TRUE, INFINITE);

	for (int i = 0; i < MAX_FILE; ++i)
	{
		DeleteCriticalSection(&g_SectionWrite[i]);
	}

	CloseHandle(g_hThreadCreateEvent);

	for (int i = 0; i < MAX_THREAD; ++i)
	{
		CloseHandle(hThread[i]);
	}

	return 0;
}


void WriteFile(int nThreadID, char chFileName, int nNum)
{
	cout<<"Thread"<<nThreadID<<": write "<<nNum<<" to file "<<chFileName<<endl;
}

DWORD __stdcall MyThreadProc(LPVOID lpThreadParameter)
{
	int nThreadID = *(int*)lpThreadParameter;
	cout<<"Thread"<<nThreadID<<"Created"<<endl;
	SetEvent(g_hThreadCreateEvent);
	char chFileName = L'A';
	int nFileID = chFileName - L'A';
	if (nThreadID > 0 && nThreadID <= MAX_THREAD)
	{
		EnterCriticalSection(&g_SectionWrite[nFileID]);
		WriteFile(nThreadID, chFileName, nThreadID);
		LeaveCriticalSection(&g_SectionWrite[nFileID]);
	}
	return 0;
}